package com.wbtech.ums.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.wbtech.ums.common.UmsConstants;
import com.wbtech.ums.objects.PostClientData;
import com.wbtech.ums.objects.PostObjActivity;
import com.wbtech.ums.objects.PostObjError;
import com.wbtech.ums.objects.PostObjEvent;
import com.wbtech.ums.objects.PostObjTag;

/**
 * 
 * SqliteDao 类描述： 数据库的业务类
 * 
 */
public class SqliteDao {

	private DBHelper dbHelper;

	public SqliteDao(Context context) {
		dbHelper = new DBHelper(context);
	}

	/**
	 *save event infor
	 * @param infos
	 * 
	 *         
	 */
	public synchronized void saveEvent(PostObjEvent event) {
		SQLiteDatabase database = dbHelper.getWritableDatabase();
		try {
			String sql = "insert into event(event_id,time,version,appkey,activity,label,acc) values (?,?,?,?,?,?,?)";
			Object[] bindArgs = { 
					event.getEvent_id(), event.getTime(),event.getVersion(),	
					event.getAppkey() ,event.getActivity(),event.getLabel(),
					event.getAcc(), 
				};
			database.execSQL(sql, bindArgs);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != database) {
				database.close();
			}
		}
	}

	/**
	 *save activity infor
	 * @param infos    
	 */
	public synchronized void saveActivity(PostObjActivity activity) {
		SQLiteDatabase database = dbHelper.getWritableDatabase();
		try {
			String sql = "insert into activity(session_id,start_millis,end_millis,duration,version,activities,appkey) values (?,?,?,?,?,?,?)";
			Object[] bindArgs = { 
					activity.getSession_id(), activity.getStart_millis(),
					activity.getEnd_millis(), activity.getDuration(),
					activity.getVersion(),activity.getActivities(),
					activity.getAppkey() };
			database.execSQL(sql, bindArgs);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != database) {
				database.close();
			}
		}
	}


	/**
	 *save error infor
	 * @param infos
	 *         
	 */
	public synchronized void saveErrorInfo(PostObjError error) {
		SQLiteDatabase database = dbHelper.getWritableDatabase();
		try {
				String sql = "insert into error(stacktrace,time,version,activity,appkey,os_version,deviceid) values (?,?,?,?,?,?,?)";
				Object[] bindArgs = { 
						error.getStacktrace(),error.getTime(),
						error.getVersion(), error.getActivity(),
						error.getAppkey(),error.getOs_version(),
						error.getDeviceid() };
				database.execSQL(sql, bindArgs);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != database) {
				database.close();
			}
		}
	}
	
	/**
	 *save Post ClientData infor
	 * @param infos
	 *         
	 */
	public synchronized void saveClientDataInfo(PostClientData data) {
		SQLiteDatabase database = dbHelper.getWritableDatabase();
		try {
				String sql = "insert into client_data(os_version,platform,language,deviceid, appkey,resolution, ismobiledevice, phonetype,"
						+ "imsi,network, time, version, userid,mccmnc,cellid, lac, modulename, devicename, "
						+ "wifimac,havebt,havewifi,havegps,havegravity, latitude,longitude) "
						+ "values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
				
				Object[] bindArgs = { 
						data.getOs_version(),data.getPlatform(),data.getLanguage(), data.getDeviceid(),data.getAppkey(),data.getResolution(),data.getIsmobiledevice(),data.getPhonetype(),
						data.getImsi(),data.getNetwork(),data.getTime(),data.getVersion(),data.getUserid(),data.getMccmnc(),data.getCellid(),data.getLac(),data.getModulename(),
						data.getDevicename(),data.getWifimac(),data.getHavebt(),data.getHavewifi(),data.getHavegps(),data.getHavegravity(),data.getLatitude(),data.getLongitude() };
				database.execSQL(sql, bindArgs);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != database) {
				database.close();
			}
		}
	}
	
	/**
	 *save tags infor
	 * @param infos
	 *         
	 */
	public synchronized void saveTagsInfo(PostObjTag tag) {
		SQLiteDatabase database = dbHelper.getWritableDatabase();
		try {
				String sql = "insert into tags(tags,deviceid,productkey) values (?,?,?)";
				Object[] bindArgs = { 
						tag.getTags(),tag.getDeviceid(),
						tag.getProductkey()};
				database.execSQL(sql, bindArgs);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != database) {
				database.close();
			}
		}
	}
	
	
	/**
	 * client Data 属于一次发送
	 * 
	 * @param 
	 * @return List<DownloadInfo>
	 */
	public synchronized PostClientData getClientDataInfos() {
		SQLiteDatabase database = dbHelper.getReadableDatabase();
		//List<PostClientData> list = new ArrayList<PostClientData>();
		PostClientData info = new PostClientData();
		Cursor cursor = null;
		try {
			String sql = "select os_version,platform,language,deviceid, appkey,resolution, ismobiledevice, phonetype,"
						+ "imsi,network, time, version, userid,mccmnc,cellid, lac, modulename, devicename, "
						+ "wifimac,havebt,havewifi,havegps,havegravity, "
						+ "latitude,longitude  from client_data ";
			cursor = database.rawQuery(sql,null);
			//while (cursor.moveToNext()) {
				
				        info.setOs_version(cursor.getString(cursor.getColumnIndex("os_version")));
				        info.setPlatform(cursor.getString(cursor.getColumnIndex("platform")));
				        info.setDeviceid(cursor.getString(cursor.getColumnIndex("deviceid")));
				        info.setAppkey(cursor.getString(cursor.getColumnIndex("appkey")));
				        info.setResolution(	cursor.getString(cursor.getColumnIndex("resolution")));
				        info.setIsmobiledevice(cursor.getInt(cursor.getColumnIndex("ismobiledevice"))==1?true:false);
				        info.setPhonetype(cursor.getInt(cursor.getColumnIndex("phonetype")));
				        info.setImsi(cursor.getString(cursor.getColumnIndex("imsi")));
				        info.setNetwork(cursor.getString(cursor.getColumnIndex("network")));
				        info.setTime(cursor.getString(cursor.getColumnIndex("time")));
				       
				        info.setUserid(cursor.getString(cursor.getColumnIndex("userid")));
				        info.setMccmnc(cursor.getString(cursor.getColumnIndex("mccmnc")));
				        info.setCellid(cursor.getString(cursor.getColumnIndex("cellid")));
				        info.setLac(cursor.getString(cursor.getColumnIndex("lac")));
				        info.setModulename(cursor.getString(cursor.getColumnIndex("modulename")));
				        info.setWifimac(cursor.getString(cursor.getColumnIndex("wifimac")));
				        info.setHavebt(	cursor.getInt(cursor.getColumnIndex("havebt")));       
				//list.add(info);
			//}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != database) {
				database.close();
			}
			if (null != cursor) {
				cursor.close();
			}
		}
		return info;
	}
	
	/**
	 * 查询最近10条数据进行批量上传
	 * 
	 * @param 
	 * @return List<DownloadInfo>
	 */
	public synchronized List<PostObjEvent> getEventInfos(int limitEnd) {
		SQLiteDatabase database = dbHelper.getReadableDatabase();
		List<PostObjEvent> list = new ArrayList<PostObjEvent>();
		Cursor cursor = null;
		try {
			String sql = "select event_id,time,version,appkey,activity,label,acc  from event order by time  limit  0,"+limitEnd;
			cursor = database.rawQuery(sql,null);
			while (cursor.moveToNext()) {
				PostObjEvent info = new PostObjEvent(
						cursor.getString(cursor.getColumnIndex("event_id")),
						cursor.getString(cursor.getColumnIndex("label")),
						cursor.getString(cursor.getColumnIndex("acc")),
						cursor.getString(cursor.getColumnIndex("time")),
						cursor.getString(cursor.getColumnIndex("activity")),
						cursor.getString(cursor.getColumnIndex("version")),
						cursor.getString(cursor.getColumnIndex("appkey"))
						);
				list.add(info);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != database) {
				database.close();
			}
			if (null != cursor) {
				cursor.close();
			}
		}
		return list;
	}

	/**
	 * 查询最近10条数据进行批量上传
	 * 
	 * @param 
	 * @return List<DownloadInfo>
	 */
	public synchronized List<PostObjActivity> getActivityInfos( int limitEnd) {
		SQLiteDatabase database = dbHelper.getReadableDatabase();
		List<PostObjActivity> list = new ArrayList<PostObjActivity>();
		Cursor cursor = null;
		try {
			String sql = "select session_id,start_millis,end_millis,duration,version,activities,appkey  from activity  order by start_millis limit  0,"+limitEnd;
			cursor = database.rawQuery(sql,null);
			while (cursor.moveToNext()) {
				PostObjActivity info = new PostObjActivity(
						cursor.getString(cursor.getColumnIndex("session_id")),
						cursor.getString(cursor.getColumnIndex("start_millis")),
						cursor.getString(cursor.getColumnIndex("end_millis")),
						cursor.getString(cursor.getColumnIndex("duration")),
						cursor.getString(cursor.getColumnIndex("version")),
						cursor.getString(cursor.getColumnIndex("activities")),
						cursor.getString(cursor.getColumnIndex("appkey"))
						);
				list.add(info);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != database) {
				database.close();
			}
			if (null != cursor) {
				cursor.close();
			}
		}
		return list;
	}

	/**
	 * 查询最近10条数据进行批量上传
	 * 
	 * @param 
	 * @return List<DownloadInfo>
	 */
	public synchronized List<PostObjError> getErrorInfos(int limitEnd ) {
		SQLiteDatabase database = dbHelper.getReadableDatabase();
		List<PostObjError> list = new ArrayList<PostObjError>();
		Cursor cursor = null;
		try {
			String sql = "select stacktrace,time,version,activity,appkey,os_version,deviceid  from error order by time  limit  0,"+limitEnd;
			cursor = database.rawQuery(sql,null);
			while (cursor.moveToNext()) {
				PostObjError info = new PostObjError(
						cursor.getString(cursor.getColumnIndex("stacktrace")),
						cursor.getString(cursor.getColumnIndex("time")),
						cursor.getString(cursor.getColumnIndex("version")),
						cursor.getString(cursor.getColumnIndex("activity")),
						cursor.getString(cursor.getColumnIndex("appkey")),
						cursor.getString(cursor.getColumnIndex("os_version")),
						cursor.getString(cursor.getColumnIndex("deviceid"))
						);
				list.add(info);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != database) {
				database.close();
			}
			if (null != cursor) {
				cursor.close();
			}
		}
		return list;
	}
	//


	public synchronized void deleteEvent(int limitEnd ) {
		SQLiteDatabase database = dbHelper.getWritableDatabase();
		try {
			database.delete("event", " time in (select time  from event limit 0,"+limitEnd+") ",null);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != database) {
				database.close();
			}
		}
	}

	public synchronized void deleteActivity( int limitEnd) {
		SQLiteDatabase database = dbHelper.getWritableDatabase();
		try {
			database.delete("activity", " start_millis in (select start_millis  from activity limit 0,"+limitEnd+") ",null);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != database) {
				database.close();
			}
		}
	}

	public synchronized void deleteError(int limitEnd ) {
		SQLiteDatabase database = dbHelper.getWritableDatabase();
		try {
			database.delete("error", " time in (select time  from error limit 0,"+limitEnd+") ",null);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != database) {
				database.close();
			}
		}
	}

	/**
	 * 关闭数据库
	 */
	public void closeDB() {
		if (null != dbHelper) {
			dbHelper.close();
		}
	}
}
